Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Ternary Operator

Ternary operator in Java

Ternary statement

The ternary statement is a conditional statement that is used to evaluate an expression and return one of two values depending on the outcome of the evaluation. The ternary statement is also known as the conditional operator or the three-way if statement. The syntax for the ternary statement is as follows:

condition ? expression1 : expression2
The condition is an expression that evaluates to a boolean value. The expression1 is the value that is returned if the condition is true. The expression2 is the value that is returned if the condition is false. Here is an example of a ternary statement:
Ternary syntax
public class Main{ public static void main(String args[]) { int age = 18; String message = age >= 18 ? "You are an adult." : "You are a minor."; System.out.println(message); } }

Output

You are an adult.
In this example, the ternary statement will print the message "You are an adult." if the value of the variable age is greater than or equal to 18. Otherwise, the ternary statement will print the message "You are a minor.". The ternary statement is a concise way to write a conditional statement. However, it is important to use it carefully, as it can make code more difficult to understand if it is not used correctly. Here are some additional things to keep in mind about the ternary statement: The ternary statement can only be used to evaluate a boolean expression. The ternary statement cannot be used to return multiple values. The ternary statement can be nested, but it is generally a good idea to avoid nesting ternary statements too deeply.

  📌TAGS

★ternary ★ternary operator ★java ★operator

Tutorials